package com.zhxy.handler;

import com.zhxy.bean.User;
import com.zhxy.constants.Constants;
import com.zhxy.result.CodeEnum;
import com.zhxy.result.R;
import com.zhxy.service.RedisService;
import com.zhxy.utils.JSONUtils;
import com.zhxy.utils.JWTUtils;
import com.zhxy.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 用于获取当前认证用户的主体信息
        User user = (User) authentication.getPrincipal();

        // 退出登录，删除redis的登录缓存信息
        redisService.removeValue(Constants.REDIS_JWT_KEY+user.getId());

        // 返回结果
        R result = R.OK(CodeEnum.user_logout);

        // 把R对象转换成json
        String json = JSONUtils.toJSON(result);

        // 将结果返回到前端
        ResponseUtils.write(response,json);
    }
}
